/*
 * Copyright (C) 2011 CrystalRange
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crystalrange.enterprise.web;

import com.googlecode.genericdao.search.Search;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.crystalrange.BaseController;
import org.crystalrange.enterprise.model.Media;
import org.crystalrange.enterprise.service.MediaService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

public class MediaListController extends BaseController {

    protected MediaService mediaService;
    protected Media selectedMedia;
    protected Listbox listboxMedia;
    protected Search searchMedia;
    protected List<Media> medias;

    public MediaService getMediaService() {
        return this.mediaService;
    }

    public void setMediaService(MediaService mediaService) {
        this.mediaService = mediaService;
    }

    public Media getSelectedMedia() {
        return this.selectedMedia;
    }

    public void setSelectedMedia(Media selectedMedia) {
        this.selectedMedia = selectedMedia;
    }

    public List<Media> getMedias() {
        return this.medias;
    }

    @Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);

        this.searchMedia = new Search(Media.class);
        this.searchMedia.setMaxResults(100);
        this.searchMedia.addFetch("createdBy");
        this.searchMedia.addFetch("updatedBy");
        this.medias = this.mediaService.search(this.searchMedia);

        component.setAttribute("controller", this);
    }

    public void onUpload$menuitemMediaUpload(UploadEvent event) throws Exception {
        this.mediaUpload(event);
    }

    public void onClick$menuitemMediaDownload(Event event) throws Exception {
        this.mediaDownload();
    }

    public void onClick$menuitemMediaEdit(Event event) throws Exception {
        this.mediaEdit();
    }

    public void onClick$menuitemMediaDelete(Event event) throws Exception {
        this.mediaDelete();
    }

    public void onClick$menuitemMediaSearch(Event event) throws Exception {
        this.mediaSearch();
    }

    public void onClick$menuitemMediaRefresh(Event event) throws Exception {
        this.mediaRefresh();
    }

    public void onUpload$toolbarbuttonMediaUpload(UploadEvent event) throws Exception {
        this.mediaUpload(event);
    }

    public void onClick$toolbarbuttonMediaDownload(Event event) throws Exception {
        this.mediaDownload();
    }

    public void onClick$toolbarbuttonMediaEdit(Event event) throws Exception {
        this.mediaEdit();
    }

    public void onClick$toolbarbuttonMediaDelete(Event event) throws Exception {
        this.mediaDelete();
    }

    public void onClick$toolbarbuttonMediaSearch(Event event) throws Exception {
        this.mediaSearch();
    }

    public void onClick$toolbarbuttonMediaRefresh(Event event) throws Exception {
        this.mediaRefresh();
    }

    public void onDoubleClickListItem(Listitem listitem) throws Exception {
        this.mediaDownload();
    }
    
    private void mediaUpload(UploadEvent event) throws Exception {
        org.zkoss.util.media.Media zkMedia = (org.zkoss.util.media.Media) event.getMedia();

        if (zkMedia != null) {
            Media media = new Media();
            media.setByteData(IOUtils.toByteArray(zkMedia.getStreamData()));
            media.setContentType(media.getContentType());
            media.setName(media.getName());
            this.mediaService.save(media, 
                    SecurityContextHolder.getContext().getAuthentication().getName());
        }

        this.medias = this.mediaService.search(this.searchMedia);
        this.binder.loadAll();
    }

    private void mediaDownload() throws Exception {
        Set<Listitem> selectedItems = this.listboxMedia.getSelectedItems();

        if (selectedItems.size() > 0) {
            if (Messagebox.YES == Messagebox.show("Delete these records?", "Delete?",
                    Messagebox.YES | Messagebox.NO, Messagebox.QUESTION)) {
                for (Listitem selectedItem : selectedItems) {
                    Media media = (Media) selectedItem.getValue();
                    Filedownload.save(media.getByteData(), media.getContentType(), media.getName());
                }
            }
        } else {
            this.message.setText("Please select at least one item!");
            this.message.setIcon("/img/exclamation.png");
        }

        this.medias = this.mediaService.search(this.searchMedia);
        this.binder.loadAll();
    }

    private void mediaEdit() throws Exception {
        if (this.selectedMedia != null) {
            this.execution.sendRedirect("~./zul/html/media.zul?Id=" + this.selectedMedia.getId().toString());
        }
    }

    private void mediaDelete() throws Exception {
        Set<Listitem> selectedItems = this.listboxMedia.getSelectedItems();

        for (Listitem selectedItem : selectedItems) {
            Media media = (Media) selectedItem.getValue();
            this.mediaService.remove(media);
        }

        this.medias = this.mediaService.search(this.searchMedia);
        this.binder.loadAll();
    }

    private void mediaSearch() throws Exception {
        this.execution.setAttribute("searchMedia", this.searchMedia);

        Window window = (Window) this.execution.createComponents("~./zul/html/mediaSearch.zul", null, null);
        window.setParent(self);
        window.doModal();

        if (this.execution.getAttribute("result") == "ok") {
            this.searchMedia = (Search) this.execution.getAttribute("searchMedia");
        }

        this.medias = this.mediaService.search(this.searchMedia);
        this.binder.loadAll();
    }

    private void mediaRefresh() throws Exception {
        this.medias = this.mediaService.search(this.searchMedia);
        this.binder.loadAll();
    }
}
